import { constantRoutes, asyncRoutes } from '@/router'

// asyncRoutes 异步路由
// roles  路由权限标识
function filterAsyncRoutes(asyncRoutes, roles) {
    let res = []
    asyncRoutes.forEach(route => {
        const tmp = { ...route }
        if (hasRoles(roles, tmp)) {
            if (tmp.children) {
                // console.log(route.children);
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })
    return res
}


function hasRoles(roles, route) {
    if (route.permit) {
        return roles.some(role => route.permit.includes(role))
    } else {
        return true
    }
}

const state = {
    addRoutes: [],
    routes: [], //完整路由
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }
}

const actions = {
    generateRoutes({ commit }, roles) {
        return new Promise((resolve, reject) => {
            let accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
            // console.log(accessedRoutes);
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    }
}


export default {
    state,
    mutations,
    actions
}